const Checker = {
	not_empty: (str) => {
		return (!str || !str.length)// Checke if it is ""、 undefined、 null 、NaN、 []
	},
	exp: (str,tpl) => {
		let s = tpl.replace('$length',str.length).replace('$len',str.length).replace('$value',"'"+str+"'");
		let result = true;
		try{
			
			result = eval(s);
			//console.log('表达式',tpl,s,result);
		}catch{
			//console.log('表达式错误',tpl,s);
		}
		
		return result;// Checke if it is ""、 undefined、 null 、NaN、 []
	},
	len: (str,params) => {
		console.log('len',str,parseInt(params[0]));
		return (str.length>=parseInt(params[0])) && (!params[1] || parseInt(params[1])==0 || str.length<=parseInt(params[1]) ) // Checke if it is ""、 undefined、 null 、NaN、 []
	},
	//匹配身份证
	idcard: (str) => {
		return RegExp(/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/).test(str);
	},
	//匹配手机号
	phone: (str) => {
		return RegExp(/^1[3456789]\d{9}$/).test(str);
	},
	phone_sub: (str) => {
		return RegExp(/^1[3456789]\d{9}([\-,]\d{4})?$/).test(str);
	},
	//匹配手机和座机
	tel: (str) => {
		return RegExp(/^(0\d{2,3}\-)?([2-9]\d{6,7})+(\-\d{1,6})?$/).test(str) ||
				 RegExp(/^1[3456789]\d{9}([\-,]\d{4})?$/).test(str)|| 
				 RegExp(/^400[0-9]{7}/).test(str)|| 
				 RegExp(/^800[0-9]{7}/).test(str);
	},
	//匹配邮箱格式
	email: (str) => {
		return RegExp(/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/).test(str);
	},
	//匹配域名
	domain: (str) => {
		return RegExp(/[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\/.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+\/.?/).test(str)
	},
	//匹配InternetURL
	url: (str) => {
		return RegExp(/http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/).test(str)
	},
	//匹配密码（密码(以字母开头，长度在6~18之间，只能包含字母、数字和下划线)）
	password: (str) => {
		return RegExp(/^[a-zA-Z]\w{5,17}$/).test(str)
	},
	//日期格式  2019-01-12
	date:(str) => {
		return RegExp(/^\d{4}-\d{1,2}-\d{1,2}/).test(str)
	},
	//匹配正数、负数、和小数
	float: (str) => {
		return RegExp(/^(\-|\+)?\d+(\.\d+)?$/).test(str)
	},
	money: (str) => {
		return RegExp(/(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/).test(str)
	},
	//匹配数字
	number: (str) => {
		return RegExp(/^[0-9]*$/).test(str)
	},
	boolean: (str) => {
		return str
	},
	true: function(value) {
		return value == true;
	},
	false: function(value) {
		return value == false;
	},
	required: (str) => {
		return str || str==='0' || str===0;
	},
	

}

class Validator {

	constructor() {
		this.rules = [];
	}
	getRule(rule,def=''){
		let params;
		if (!rule) rule = def;
		if (rule.indexOf('$')>=0){
			params = rule;
			rule = 'exp'
		}else{
			let p =rule.split('=');
			params = [];
			if (p.length>1){
				rule = p[0];
				params = p[1].split(',');
			}
		}

		return {rule:rule,params:params};
	}
	valueIs(value,rule,params={}){
		let r = this.getRule(rule);
		if (r && Checker[r.rule] && Checker[r.rule](value,params)){
			return true;
		}else{
			return false;
		}
	}
	is(value,rule,tip='') {
		let r = this.getRule(rule);
		let item = {value:value,rule:r.rule,params:r.params,tip:tip};
		//console.log('item',item);
		this.rules.push(item)
		return this;
	}
	start(){
		this.rules = [];
		return this;
	}
	//通过refs检测，需要设置字段标题，ref = phone class=required rule=phone
	check(refs,data){
		let item,error=false;
		let el,r,name,p,params,ref,tip,field,rule,$class,value;
		//console.log('refs',refs);
		for (field in refs){
			ref = Array.isArray(refs[field])?refs[field][0]:refs[field];
			if (!ref) continue;
			value = field in data?data[field]:'';
			if (ref.getAttribute && ref.isCheckText && ref.isCheckText()){
				el = ref;
				name = el.getAttribute("title").replace(':','').replace('：','');
				$class = el.getAttribute("class");
				rule = el.getAttribute("rule");
				tip = el.getAttribute("tip");
			}else if ('$el' in ref){
				el = ref.$el;
				if (!el || !el.getAttribute){
					continue;
				}
				name = el.textContent.replace(':','').replace('：','');
				$class = el.getAttribute("class");
				rule = el.getAttribute("rule");
				tip = el.getAttribute("tip");				
			}else if ('class' in ref && 'field' in ref){
				name = (ref['title']||'').replace(':','').replace('：','');
				$class = ref['class'];
				rule = (ref['rule']||'');
				tip = (ref['tip']||'');	
				value = ref['value']?ref['value']:value;	
			}
			//console.log($class);
			if (!$class || ($class.split(' ').indexOf('required')<0 && !rule)){
				continue;
			}
			
			r = this.getRule(rule,'required');
			
			if (Checker[r.rule] && !Checker[r.rule](value,r.params)){
				tip = tip?tip:'请按要求填写【'+name+'】';
				if (tip){
					uni.showToast({
						title:tip,
						icon:'none'
					});
				}
				error = field;
				break;
			} 
		}
		return error;
		
	}
	execute(){
	
		let item,error=false;
		for(var i=0;i<this.rules.length;i++){
			item = this.rules[i];
			
			if (Checker[item.rule] && !Checker[item.rule](item.value,item.params)){
				
				if (item.tip){
					uni.showToast({
						title:item.tip,
						icon:'none'
					});
				}
				error = item;
				break;
			} 
		}
		this.rules = [];
		if (error){
			//console.log('check.eroror',error);
			return error;
		}else{
			return false;
		}
		
	}
	
}


const proxy = cache => { // 递归代理器
	return new Proxy(cache, {
		get(target, key) {  //代理get
			if (key in target){
				return target[key]
			}else{
				console.log(key);
				return target.get(key)
			}
		},
		deleteProperty (target, key) { // 代理 delete
			target.remove(key);
			return true
		}
	})
}

export default new Validator;
